const md5 = require('mymd5.js');
var appsecret ="u4sr359bft4h5a2cg0fn9b2fhfd2ip6a";
var App_Key ="sjune_yuren";
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

//秒转时间
function secondToDate(miao) {

    miao = parseInt(miao);// 秒

  if (miao < 60) {
    return "00:" + miao;
  }
  else if(miao>=60 && miao<=3600)
  {
    var fen = parseInt(miao / 60);
    var  newmiao = parseInt(miao % 60);

     return   fen+":"+newmiao;
  }
  else
  {
    var h = Math.floor(miao / 3600) < 10 ? '0' + Math.floor(miao / 3600) : Math.floor(miao / 3600);
    var m = Math.floor((miao / 60 % 60)) < 10 ? '0' + Math.floor((miao / 60 % 60)) : Math.floor((miao / 60 % 60));
    var s = Math.floor((miao % 60)) < 10 ? '0' + Math.floor((miao % 60)) : Math.floor((miao % 60));
    var ret="";
    if(h!="00"&& m!="00" )
    {
      ret= h + ":" + m + ":" + s;
    }
    else
    {
      ret =   m + ":" + s;
    }

    return ret;
  }




}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function sortCharter(a, b) {
  if (a.toString().toUpperCase() > b.toString().toUpperCase()) {
    return 1;
  }
  else if (a.toString().toUpperCase() == b.toString().toUpperCase()) {
    return 0;
  }
  else {
    return -1;
  }
}

function objKeySort(obj) {//排序的函数
  var newkey = Object.keys(obj).sort(sortCharter);
  //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
  var newObj = {};//创建一个新的对象，用于存放排好序的键值对
  for (var i = 0; i < newkey.length; i++) {//遍历newkey数组
    newObj[newkey[i]] = obj[newkey[i]];//向新创建的对象中按照排好的顺序依次增加键值对
  }
  return newObj;//返回排好序的新对象
}
String.prototype.PadLeft = function (len, charStr) {
  var s = this + '';
  return new Array(len - s.length + 1).join(charStr, '') + s;
}

//创建sign
function create_sign(data) {

 // console.log("1、排序前create_sign0");
 // console.log(data);
  //1、排序
  var news_data = objKeySort(data);
 // console.log("1、排序后create_sign111");
 // console.log(news_data);
  //2.拼接
  var txt="";
  var newkey = Object.keys(news_data);
  //console.log("for内部===k-v");
  for (var i = 0; i < newkey.length; i++) {//遍历newkey数组

    txt = txt + newkey[i].length.toString().PadLeft(2, '0');
    txt=txt+"-";
    txt = txt + newkey[i];
    txt = txt + ":";
   // console.log(newkey[i]);
   // console.log(data[newkey[i]]);
    var aaa = String(news_data[newkey[i]]);
    var bbb = aaa.length.toString();
    var ccc = bbb.PadLeft(4, '0');
    txt = txt + ccc;
    // txt = txt + news_data[newkey[i]].toString().length.toString().PadLeft(4,'0');
    txt = txt + "-";
    txt = txt + news_data[newkey[i]];

    if (i < (newkey.length-1))
    {
      txt = txt + ";";
    }
  }
  //console.log("for内部===3.追加私钥appsecret");
  //3.追加私钥appsecret
  //console.log(txt);
 // console.log("appsecret=" + appsecret);
  txt = txt + appsecret;
  // console.log("加密前 txt=" + txt);
  //4.md5加密
  txt = md5.md5(txt);
  return txt;
}



function request(url, method = 'POST', data = {}, message='') {
  wx.showNavigationBarLoading()
  if (message != "") {
    wx.showLoading({
      title: message,
    })
  }

  let header = {
    'content-type': 'application/x-www-form-urlencoded'
  };

  var timestamp = new Date().getTime();
  data.Timestamp = timestamp;
  data.App_Key = App_Key;
  var sign = create_sign(data);
  data.sign = sign;

// console.log(url,'url');
// console.log(method,'method');
// console.log(data,'data');




  let token = wx.getStorageSync('token') || '';
  if (token) {
    header['X-MXAPI-Authorization'] = token
  }

  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      method: method,
      data: data,
      header: header,
      success: function (res) {
        //console.log(res);

        if (res.data.status != -100) {
          resolve(res.data);
        } else {
          reject(res.data);
        }

        wx.hideNavigationBarLoading()
        if (message != "") {
          wx.hideLoading()
        }

      },
      fail: function (err) {
        wx.hideNavigationBarLoading()
        if (message != "") {
          wx.hideLoading()
        }
        wx.showToast({
          title: '网络加载失败',
        });


      }
    });
  });
}


function showToast(title, type = 'error') {
  let image = '';
  switch (type) {
    case 'error':
      image = '/images/icon_error.png'
      break;
    case 'success':
      image = '/images/icon_success.png'
      break;
    case 'warning':
      image = '/images/icon_warning.png'
      break;
  }
  wx.showToast({
    title: title,
    image: image,
    duration: 0,
    mask: true,
    success: function (res) { },
    fail: function (res) { },
    complete: function (res) { },
  })
}



module.exports = {
  formatTime: formatTime,
  secondToDate: secondToDate,
  request: request,
  showToast: showToast,
}

